/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.db.cfg;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;

import com.edi.util.ConfigHelper;
import com.edi.util.XMLProperties;

public class Configuration implements Serializable {
	private static final Log log = LogFactory.getLog(Configuration.class);
	protected Properties properties = new Properties();

	// private static Environment envrionment=new Environment();

	public Configuration() throws Exception {
		// InputStream stream = getConfigurationInputStream( "/project.xml" );
		// doConfig(stream);
	}
	
	public Configuration(Properties properties){
		this.properties = properties;
	}
	
	public Configuration(String filePath) throws Exception {
		InputStream stream = getConfigurationInputStream(filePath);
		doConfig(stream);
	}

	public Configuration(Document doc) throws Exception {
		configutation(doc);
	}

	public Configuration configutation(Document doc) {
		Element pNode = doc.getRootElement().element("DBConfig").element(
				"props");
		log.info(" pNode =" + pNode);
		if (pNode != null) {
			Iterator iter = pNode.elementIterator("prop");
			while (iter.hasNext()) {
				Element node = (Element) iter.next();
				String id = node.attributeValue("id");
				String caption = node.attributeValue("caption");
				String datatype = node.attributeValue("datatype");
				String value = node.attributeValue("value");
				log.debug(" id =" + id + " // caption =" + caption
						+ " // datatype =" + datatype + " // value =" + value);
				if (!id.startsWith("edidb"))
					properties.setProperty("edidb." + id, value);
				else
					properties.setProperty(id, value);
			}
			// envrionment.addProps(properties);
		}
		return this;
	}

	protected Configuration doConfig(InputStream stream) {
		try {
			XMLProperties xmlProps = new XMLProperties(stream);
			if (xmlProps.document == null) {
				log.error(" doConfig 发生异常，dom 为空！");
				throw new RuntimeException(" doConfig 发生异常，dom 为空！");
			}
			configutation(xmlProps.document);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				stream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return this;
	}

	protected InputStream getConfigurationInputStream(String resource)
			throws Exception {

		log.info("Configuration resource: " + resource);

		return ConfigHelper.getResourceAsStream(resource);

	}

	/**
	 * 获取一个属性值
	 * 
	 * @param propertyName
	 * @return
	 */
	public String getProperty(String propertyName) {
		return properties.getProperty(propertyName);
	}

	/**
	 * 添加一个属性
	 */
	public void setProperty(String key, String propertValue) {
		properties.setProperty(key, propertValue);
	}

	/**
	 * 返回config的propertys
	 * 
	 * @return
	 */
	public Properties getConfigPropertys() {
		return properties;
	}

	public boolean equals(Configuration configure) { 
		String thisJndiName=this.getProperty(Environment.JNDINAME);
		String cfgJndiName=configure.getProperty(Environment.JNDINAME);
		String thisServer=this.getProperty(Environment.SERVER);
		String cfgServer=configure.getProperty(Environment.SERVER);
		String thisDbName=this.getProperty(Environment.DBNAME);
		String cfgDbName=configure.getProperty(Environment.DBNAME); 
		String thisUser=this.getProperty(Environment.USERNAME);
		String cfgUser=configure.getProperty(Environment.USERNAME);
		String thisPassword=this.getProperty(Environment.PASSWD);
		String cfgPassword=configure.getProperty(Environment.PASSWD); 
		if(StringUtils.isNotBlank(thisJndiName)){
			if(StringUtils.isNotBlank(cfgJndiName)){
				if(StringUtils.equalsIgnoreCase(thisJndiName,cfgJndiName))
					return true;
				else
					return false;
			}
			else
				return false;
		} else{
			if(StringUtils.isNotBlank(cfgJndiName))
				return false;
			else{
				if((StringUtils.equalsIgnoreCase(thisServer,cfgServer))
						&&StringUtils.equalsIgnoreCase(StringUtils.replace(thisDbName, "localhost", "127.0.0.1"),StringUtils.replace(cfgDbName, "localhost", "127.0.0.1"))
						&&StringUtils.equalsIgnoreCase(thisUser,cfgUser)
						&&StringUtils.equalsIgnoreCase(thisPassword,cfgPassword)
						)
					return true;
				else
					return false;
					
			}
		}   
	}
	public void setProperties(String key,String value,String defaultValue){
		if(StringUtils.isBlank(value)&&StringUtils.isBlank(defaultValue))
			throw new RuntimeException("value  defaultValue 为空！");
		if(value!=null)
			properties.setProperty(key, value);
		else if(defaultValue!=null)
			properties.setProperty(key, defaultValue);
		
	}

}
